using Microsoft.EntityFrameworkCore;
using UniversalAdmin.Application.Dtos.File;
using UniversalAdmin.Application.Services.Interfaces;
using UniversalAdmin.Domain.Repositories;
using FileEntity = UniversalAdmin.Domain.Entities.App.File;

namespace UniversalAdmin.Application.Services.Implementations;

/// <summary>
/// 文件服务实现
/// </summary>
public class FileService : IFileService
{
    private readonly IRepositories<FileEntity> _fileRepository;
    private readonly IRepositories<UniversalAdmin.Domain.Entities.App.User> _userRepository;

    public FileService(
        IRepositories<FileEntity> fileRepository,
        IRepositories<UniversalAdmin.Domain.Entities.App.User> userRepository)
    {
        _fileRepository = fileRepository;
        _userRepository = userRepository;
    }

    public async Task<FileDto> SaveFileInfoAsync(string fileName, string originalName, string contentType, long size, string filePath, Guid? userId = null)
    {
        // 创建文件实体
        var fileEntity = new FileEntity
        {
            Name = fileName,
            OriginalName = originalName,
            Path = filePath,
            Size = size,
            MimeType = contentType,
            UserId = userId
        };

        var savedFile = await _fileRepository.CreateAsync(fileEntity);

        return new FileDto
        {
            Id = savedFile.Id,
            Name = savedFile.Name,
            OriginalName = savedFile.OriginalName,
            Path = savedFile.Path,
            Url = filePath, // 这里直接返回路径，URL构建在Controller中处理
            Size = savedFile.Size,
            MimeType = savedFile.MimeType,
            UserId = savedFile.UserId,
            CreatedAt = savedFile.CreatedAt
        };
    }

    public async Task<FileDto?> GetByIdAsync(Guid id)
    {
        var file = await _fileRepository.GetByIdAsync(id);
        if (file == null || file.IsDeleted)
            return null;

        var user = file.UserId.HasValue ? await _userRepository.GetByIdAsync(file.UserId.Value) : null;

        return new FileDto
        {
            Id = file.Id,
            Name = file.Name,
            OriginalName = file.OriginalName,
            Path = file.Path,
            Url = file.Path, // URL构建在Controller中处理
            Size = file.Size,
            MimeType = file.MimeType,
            UserId = file.UserId,
            Username = user?.Username,
            CreatedAt = file.CreatedAt
        };
    }

    public async Task<(IEnumerable<FileDto> Items, int TotalCount)> GetFilesAsync(
        int pageIndex = 1,
        int pageSize = 10,
        string? keyword = null,
        string? mimeType = null,
        Guid? userId = null)
    {
        var query = _fileRepository.Table.Where(f => !f.IsDeleted);

        // 应用筛选条件
        if (!string.IsNullOrEmpty(keyword))
        {
            query = query.Where(f => f.Name.Contains(keyword) || f.OriginalName.Contains(keyword));
        }

        if (!string.IsNullOrEmpty(mimeType))
        {
            query = query.Where(f => f.MimeType != null && f.MimeType.Contains(mimeType));
        }

        if (userId.HasValue)
        {
            query = query.Where(f => f.UserId == userId.Value);
        }

        var totalCount = await query.CountAsync();

        var files = await query
            .OrderByDescending(f => f.CreatedAt)
            .Skip((pageIndex - 1) * pageSize)
            .Take(pageSize)
            .ToListAsync();

        var fileDtos = new List<FileDto>();
        foreach (var file in files)
        {
            var user = file.UserId.HasValue ? await _userRepository.GetByIdAsync(file.UserId.Value) : null;

            fileDtos.Add(new FileDto
            {
                Id = file.Id,
                Name = file.Name,
                OriginalName = file.OriginalName,
                Path = file.Path,
                Url = file.Path, // URL构建在Controller中处理
                Size = file.Size,
                MimeType = file.MimeType,
                UserId = file.UserId,
                Username = user?.Username,
                CreatedAt = file.CreatedAt
            });
        }

        return (fileDtos, totalCount);
    }

    public async Task<bool> DeleteFileAsync(Guid id)
    {
        var file = await _fileRepository.GetByIdAsync(id);
        if (file == null || file.IsDeleted)
            return false;

        // 软删除文件记录
        await _fileRepository.DeleteAsync(file);
        return true;
    }

    public async Task<FileEntity?> GetFileEntityAsync(Guid id)
    {
        var file = await _fileRepository.GetByIdAsync(id);
        return file != null && !file.IsDeleted ? file : null;
    }
}
